package com.wanxi.dangdang.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanxi.dangdang.mapper.EsScenicRepository;
import com.wanxi.dangdang.mapper.ScenicMapper;
import com.wanxi.dangdang.model.pojo.Area;
import com.wanxi.dangdang.model.pojo.Scenic;
import com.wanxi.dangdang.model.vo.*;
import com.wanxi.dangdang.service.ScenicService;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import static org.elasticsearch.index.query.QueryBuilders.matchQuery;

@Service("scenicService")
public class ScenicServiceImpl implements ScenicService {
    @Autowired
    private ScenicMapper scenicMapper;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private EsScenicRepository esScenicRepository;

    @Override
    public ScenicFindByIdVO findById(Long id) {
        ScenicFindByIdVO scenic = scenicMapper.findById(id);

        return scenic;
    }

    @Override
    public PageInfo<ScenicPageVO> findPage(PageScenicDimVO pageScenicDimVO, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        if (pageScenicDimVO.getArea() != null) {
            Long districtId = areaSplit(pageScenicDimVO.getArea());
            pageScenicDimVO.setDistrictId(districtId);
        }
        List<ScenicPageVO> list = scenicMapper.findPage(pageScenicDimVO);
        return new PageInfo<>(list);
    }

    @Override
    public void add(AddScenicVO addScenicVO) {
        //通过省市区找到区id
        Long districtId = areaSplit(addScenicVO.getArea());
        addScenicVO.setDistrictId(districtId);
//        景区编号  时间戳+4个随机数
        Random r = new Random();
        String scenicNumber = new Date().getTime() + String.valueOf(r.nextInt(10000));
        scenicMapper.add(addScenicVO, scenicNumber);
    }

    @Override
    public AddScenicVO backFindById(Long scenicId) {
        AddScenicVO addScenicVO = scenicMapper.backFindById(scenicId);
        Long districtId = addScenicVO.getDistrictId();
        //通过景区的区id找到地区信息
        Area area = scenicMapper.findAreaInfoByDistrictId(districtId);
        if (area == null) {
            return null;
            //Log.Info()
        }
        addScenicVO.setArea(area.getProvince().concat(",").concat(area.getCity()).concat(",").concat(area.getArea()));
        System.out.println(addScenicVO.getArea());
        return addScenicVO;
    }

    @Override
    public void delete(Long scenicId) {
        scenicMapper.delete(scenicId);
    }

    @Override
    public void backUpdateStatus(Long scenicId) {
        scenicMapper.backUpdateStatus(scenicId);
    }

    @Override
    public PageInfo<Scenic> backFindPage(FindPageScenicVO findPageScenicVO) {
        PageHelper.startPage(findPageScenicVO.getPageNum(), findPageScenicVO.getPageSize());
        List<Scenic> list = scenicMapper.backFindPage(findPageScenicVO);
        return new PageInfo<>(list);
    }

    //       通过景区表找到销量前五景区
    @Override
    public List<HighSalesCityVO> findHighSalesCityBySales() {
        return scenicMapper.findHighSalesCityBySales();
    }

    @Override
    public List<SumScenicVO> findHighSumScienceByCity() {
        return scenicMapper.findHighSumScienceByCity();
    }

    @Override
    public void backUpdate(AddScenicVO addScenicVO, Long id) {
        //先找到区id
        Long s = areaSplit(addScenicVO.getArea());
        addScenicVO.setDistrictId(s);
        scenicMapper.backUpdate(addScenicVO, id);
    }

    @Override
    public PageInfo findByDistributorId(PageScenicDimVO pageScenicDimVO, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<BUserScenicVO> list = scenicMapper.findByDistributorId(pageScenicDimVO);
        return new PageInfo<>(list);
    }

    @Override
    public void updateStatus(Long distributorId, Long scenicId) {
        scenicMapper.updateStatus(distributorId, scenicId);

    }

    @Override
    public void deleteScenicByBUser(Long distributorId, Long scenicId) {
        Long storeId =scenicMapper.findStoreIdByUserid(distributorId);
        scenicMapper.deleteScenicByBUser(storeId, scenicId);
    }

    @Override
    public String saveToMyStore(Long distributorId, Long scenicId) {
        Integer result = scenicMapper.saveToMyStore(distributorId, scenicId);
        return result > 0 ? "success" : "error";
    }

    @Override
    public PageInfo PlatformRecommend() {
        List<ScenicPageVO> list = scenicMapper.PlatformRecommend();
        return new PageInfo<>(list);
    }

    /**
     * @Author:YanZhengYi
     * @Description: 通过省市区找到区的id
     * @Params: area是"省，市，区"
     * @Date: 15:18 2021/9/2
     */
    private Long areaSplit(String area) {
        String[] split = area.split(",");
        Area area1 = new Area();
        area1.setProvince(split[0]);
        area1.setCity(split[1]);
        area1.setArea(split[2]);
        return scenicMapper.findDistrictIdByArea(area1);
    }

    @Override
    public Integer increaseSale(Long scenicId, Integer num) {
        return scenicMapper.increaseSale(scenicId, num);
    }


    //  保存到  es
    public String saveAll() {
        List<Scenic> scenicList = scenicMapper.esFindAll();
        esScenicRepository.saveAll(scenicList);
        return "success";
    }

    /**
     * @Author:YanZhengYi
     * @Description: 查找库存表中的库存，找不到则查景区表的原始库存并返回，同时在库存表新增一个记录，找到后直接返回库存量，返回-1则有多个添加数据的操作，出错
     * @Params: scenic_id景区id, date字符串格式的日期
     * @Date: 11:13 2021/9/4
     */
    @Override
    public Integer findRepertory(Long scenicId, Long date) {
        String result1 = new SimpleDateFormat("yyyy-MM-dd").format(new Date(date));
        Integer repertory = scenicMapper.findRepertory(scenicId, result1);
        if (repertory == null) {
            Date date1 = new Date(date);
            Timestamp timeStamp = new Timestamp(date1.getTime());
            repertory = scenicMapper.backFindById(scenicId).getOriginRepertory();
            try {
                scenicMapper.addRepertory(scenicId, repertory, timeStamp);
            } catch (Exception e) {
                return -1;
            }
            return repertory;
        }
        return repertory;
    }

    @Override
    public boolean addRepertory(Long scenicId, Long date, Integer number) {
        String result = new SimpleDateFormat("yyyy-MM-dd").format(new Date(date));
        Integer recoding = scenicMapper.increaseRepertory(scenicId, result, number);
        return recoding == 1;
    }

    public boolean reduceRepertory(Long scenicId, Long date, Integer number) {
        String result = new SimpleDateFormat("yyyy-MM-dd").format(new Date(date));
        Integer recoding = scenicMapper.decreaseRepertory(scenicId, result, number);
        return recoding == 1;
    }

    @Override
    public Double findCommissionRateByScenicId(Long id) {
        return scenicMapper.findCommissionRateByScenicId(id);
    }

    @Override
    public String findRepetitionStore(Long id ,Long scenicId) {
        List<ScenicIdVO> list = scenicMapper.findRepetitionStore(id, scenicId);
//        List list = new ArrayList<>();
//        list.add(result);
        if(list.size()>0){
            return "false";
        }
        return "true";
    }

    //es查询全部
    @Override
    public Page<Scenic> findHomePage(Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of((pageNum - 1), pageSize);
        Page<Scenic> result = esScenicRepository.findAll(pageable);
        return result;
    }

    //es 高亮查询
    @Override
    public SearchHits<Scenic> findByNameHighLight(String keyword, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of((pageNum - 1), pageSize);
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(matchQuery("title", keyword))
                .withPageable(pageable)
                .withHighlightFields(
                        new HighlightBuilder.Field("title").preTags("<font color=\"red\">").postTags("</font>")
                )
                .build();
        SearchHits<Scenic> searchHits = elasticsearchRestTemplate.search(query, Scenic.class);
        return searchHits;
    }


}
